using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Deepcode.Flux.Core.Services.FileSystem;
using Deepcode.Flux.Core.Systems.Asset;

public partial class Private_Asset_Files : Deepcode.Flux.Core.UI.AdministrationModulePage
{
	#region Permission Code Override
	public override string RequiredPermissionCode { get { return "FluxAmAccess"; } }
	#endregion
	#region Rootpath and AssetBrowse mode
	/// <summary>
	/// Specify the root path to use
	/// </summary>
	protected string RootPath
	{
		get
		{
			object o = Session["AssetRootPath"];
			if (o == null) return "~/assets";
			return (string)o;
		}
	}
	/// <summary>
	/// Determines whether in browse mode or not
	/// browse mode will return a filename back to 
	/// the calling template
	/// </summary>
	protected bool AssetBrowse
	{
		get
		{
			object o = Session["AssetBrowse"];
			if (o == null) return false;
			return (bool)o;
		}
	}
	#endregion
	#region ViewState and Properties
	/// <summary>
	/// Store the path passed in if appropriate
	/// </summary>
	protected string Path
	{
		get
		{
			object o = ViewState["Path"];
			if( o == null ) return "";
			return (string) o;
		}
		set
		{
			ViewState["Path"] = value;
		}
	}
	/// <summary>
	/// Get the current file mask
	/// </summary>
	protected string CurrentFileMask
	{
		get
		{
			return UserSetting("ASSETFILEMASK", "*.*");
		}
	}
	#endregion
	#region Page Load Event
	/// <summary>
	/// Page Load event
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			// Load path data
			Path = GetAttribute("Path", "");
			// If no path passed in, user last known path from registry
			if (Path == "")
				Path = UserSetting("ASSETMANAGERLASTPATH", this.RootPath);

			// Ensure path exists - default to assets if not
			string fullpath = Server.MapPath(Path);
			if (!System.IO.Directory.Exists(fullpath))
			{
				if (System.IO.File.Exists(fullpath))
				{
					Path = Path.Substring(0, Path.LastIndexOf('/'));
					fullpath = Server.MapPath( Path );
					if( !System.IO.Directory.Exists( fullpath )) Path=this.RootPath;
				}
				else
					Path = this.RootPath;
			}

			// If the selected path is not inside of the specified rootpath, use rootpath
			if( ! Path.StartsWith(this.RootPath) ) Path = this.RootPath;

			// Display the path in the panel
			mainPanel.Title = Path.Substring(1);

			// File mask panels
			filemask.Text = CurrentFileMask;
			
			// Bind the data
			BindData();
		}
	}
	#endregion
	#region Page_Init Event
	/// <summary>
	/// Capture events
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Init(object sender, EventArgs e)
	{
		_data.SelectedIndexChanged += new EventHandler(_data_SelectedIndexChanged);
		_data.SortCommand += new DataGridSortCommandEventHandler(_data_SortCommand);
		_data.SortDirectionCommand += new Deepcode.Flux.Core.UI.Controls.StandardDataGrid.OnSortDirectionCommand(_data_SortDirectionCommand);
		availablemasks.SelectedIndexChanged += new EventHandler(availablemasks_SelectedIndexChanged);
	}
	#endregion
	#region Data Binding
	/// <summary>
	/// Load clients into the grid
	/// </summary>
	private void BindData()
	{
		// Bind up the file listing
		FileScanService fss = new FileScanService();
		FileSortService fsort = new FileSortService();
		List<System.IO.FileInfo> rawdata = fss.GetFilesInWebPath(this.Path, CurrentFileMask);
		_data.DataSource = fsort.SortData( rawdata, _data.CurrentSort, _data.CurrentSortDirection );
		_data.DataBind();

		// Get and bind the available filter masks
		AssetFilters filters = new AssetFilters();
		availablemasks.Items.Clear();
		availablemasks.Items.Add( new ListItem("User defined mask", ""));
		foreach( AssetFilter f in filters.GetAllFilters() )
			availablemasks.Items.Add( new ListItem( f.Text, f.Mask ) );

		// Set value
		try { availablemasks.SelectedValue = CurrentFileMask; }
		catch { availablemasks.SelectedValue = ""; }

		if( ! AssetBrowse ) _data.Columns[3].Visible = false;
	}

	void _data_SortDirectionCommand(object source, string SortExpression, Deepcode.Flux.Core.Data.DataSortDirection Direction)
	{
		BindData();
	}

	void _data_SortCommand(object source, DataGridSortCommandEventArgs e)
	{
		BindData();
	}

	#endregion
	#region User Interaction
	/// <summary>
	/// Selected file has changed
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	void _data_SelectedIndexChanged(object sender, EventArgs e)
	{
		if (_data.SelectedIndex == -1)
		{
			// open actions panel for the selected folder
			ClientScript.RegisterStartupScript(typeof(Private_Asset_Files),
				"loadActions",
				"this.parent.loadActions('" + this.Path + "');",
				true);
		}
		else
		{
			string Selection = String.Format("{0}/{1}", this.Path, _data.DataKeys[_data.SelectedIndex]);
			Selection = Selection.Replace("'", "\\'");

			// open actions panel for the selected folder
			ClientScript.RegisterStartupScript(typeof(Private_Asset_Files),
				"loadActions",
				"this.parent.loadActions('" + Selection + "');",
				true);
		}
	}
	/// <summary>
	/// Apply button clicked for file masks
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnApplyMaskClick(object sender, EventArgs e)
	{
		this.SetUserSetting("ASSETFILEMASK", filemask.Text);
		this.BindData();
	}
	/// <summary>
	/// New mask selected
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	void availablemasks_SelectedIndexChanged(object sender, EventArgs e)
	{
		if( availablemasks.SelectedValue == "" ) return;
		this.SetUserSetting("ASSETFILEMASK", availablemasks.SelectedValue);
		filemask.Text = availablemasks.SelectedValue;
		BindData();
	}
	#endregion
	#region Custom Databinders
	/// <summary>
	/// Cache of the icons loader
	/// </summary>
	private AssetIcons _icons = null;
	protected AssetIcons ICONS
	{
		get
		{
			if( _icons == null ) _icons = new AssetIcons();
			return _icons;
		}
	}
	/// <summary>
	/// Get icon HTML based on the FileInfo passed in
	/// </summary>
	/// <param name="o"></param>
	/// <returns></returns>
	public string GetIcon(object o)
	{
		return ICONS.GetIconFileForExtension( ((System.IO.FileInfo) o).Extension );
	}
	/// <summary>
	/// Get the length HTML based on the FileInfo passed in
	/// </summary>
	/// <param name="o"></param>
	/// <returns></returns>
	public string GetLength(object o)
	{
		System.IO.FileInfo fi = (System.IO.FileInfo) o;
		long l = fi.Length;
		string type = " bytes";

		if (l > 1024)
		{
			l = l / 1024;
			type = " Kb";
		}

		if (l > 1024)
		{
			l = l / 1024;
			type = " Mb";
		}

		if (l > 1024)
		{
			l = l / 1024;
			type = " Gb";
		}

		return String.Format("{0}{1}", l, type);
	}
	/// <summary>
	/// Returns the link necessary to select this file in an asset control
	/// </summary>
	/// <param name="o"></param>
	/// <returns></returns>
	public string GetSelectLink(object o)
	{
		System.IO.FileInfo fi = (System.IO.FileInfo) o;
		if( fi == null ) return "";

		string rootpath = Server.MapPath(this.RootPath);
		string assetFile = fi.FullName;

		if( ! assetFile.StartsWith( rootpath )) return "";
		assetFile = ((string) (this.RootPath + assetFile.Substring( rootpath.Length ))).Replace('\\', '/');

		// Build up a link to select this file
		string href = String.Format(
			"<a href=\"javascript:ReturnFile('{0}');\" class=\"safelink\">Select</a>",
			assetFile);

		return href;
	}
	#endregion
}
